import { MongoClient } from "mongodb";

const url = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(url);

async function run() {
  try {
    await client.connect();
    const db = client.db("hello");
    const res = await db.command({ ping: 1 }); // 测试数据库是否成功
    console.log("connected", res);
    const userCollection = db.collection("user");
    const teamCollection = db.collection("team");
    const pipeLine = [
      { $match: { name: "Nets" } },
      {
        $lookup: {
          from: "user",
          localField: "players",
          foreignField: "_id",
          as: "newPlayers",
        },
      },
    ];
    const teamWithPlayers = await teamCollection.aggregate(pipeLine).toArray();
    console.log("🚀 ~ run ~ teamWithPlayers:", teamWithPlayers[0]);

    const pipeLine2 = [
      {
        $match: { team: { $exists: true } },
      },
      {
        $lookup: {
          from: "team",
          localField: "team",
          foreignField: "_id",
          as: "team",
        },
      },
    ];

    const players = await userCollection.aggregate(pipeLine2).toArray();
    console.log(players[0]);
  } catch (error) {
    console.error("error", error);
  } finally {
    await client.close();
  }
}

run();
